
document.getElementById('image-form').addEventListener('submit', async (e) => {
    e.preventDefault();

    // --- 安全警告: API密钥直接暴露在前端代码中 ---
    const apiKey = "sk-2hMCxFsPUx2eWVGCXQJpuHpMaXKzagSUd5hgqTGIsgOylD4e";
    const apiUrl = "https://apipro.maynor1024.live/v1/images/generations";
    // ----------------------------------------------------

    const form = e.target;
    const prompt = form.prompt.value;
    const imageFile = form.image.files[0];
    const resultContainer = document.getElementById('result-container');
    const resultImage = document.getElementById('result-image');
    const generateBtn = form.querySelector('.generate-btn');

    if (!prompt) {
        alert('Please enter a prompt.');
        return;
    }

    // 显示加载状态
    generateBtn.disabled = true;
    generateBtn.textContent = 'Generating...';
    resultContainer.classList.add('hidden');

    // 准备API请求的payload
    const payload = {
        model: "doubao-seedream-4-0-250828",
        prompt: prompt,
        size: "2K", // 或者根据需要调整
        response_format: "url",
        watermark: true
    };

    // 读取并转换图片为Base64
    const readImageAsBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
            reader.readAsDataURL(file);
        });
    };

    try {
        if (imageFile) {
            const base64Image = await readImageAsBase64(imageFile);
            payload.image = base64Image;
        }

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: response.statusText }));
            throw new Error(`API error (${response.status}): ${errorData.message || 'Unknown error'}`);
        }

        const data = await response.json();

        if (data.data && data.data[0] && data.data[0].url) {
            resultImage.src = data.data[0].url;
            resultContainer.classList.remove('hidden');
        } else {
            throw new Error('No image URL found in the API response.');
        }

    } catch (error) {
        console.error('Error:', error);
        alert(`An error occurred: ${error.message}`);
    } finally {
        // 恢复按钮状态
        generateBtn.disabled = false;
        generateBtn.textContent = 'Generate';
    }
});
